package com.ITArmy.util;


import com.ITArmy.common.ServerResponse;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

public class SendEmail {
    public ServerResponse sendEmail(String targetEmail, HttpServletRequest req) {
        isEmail check = new isEmail();
        String code = achieveCode();
        if (check.isEmail(targetEmail)) {
            try {
                String from = "1095652242@qq.com";//发送邮件的邮箱账号
                String to = targetEmail;//对方邮箱
                String subject = "ITArmy提醒您:您的验证码如下，一分钟内有效";//标题
                String body = code;//这是发送的验证码
                String smtpHost = "smtp.qq.com";//smtp.qq.com/smtp.sohu.com
                Properties props = new Properties();
                props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议（JavaMail规范要求）
                props.setProperty("mail.smtp.host", smtpHost); // 发件人的邮箱的 SMTP服务器地址
                props.setProperty("mail.smtp.auth", "true"); // 请求认证，参数名称与具体实现有关
                // 创建Session实例对象
                Session session = Session.getDefaultInstance(props);
                // 创建MimeMessage实例对象
                MimeMessage message = new MimeMessage(session);
                // 设置发件人
                message.setFrom(new InternetAddress(from));
                // 设置收件人
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
                // 设置发送日期
                message.setSentDate(new Date());
                // 设置邮件主题
                message.setSubject(subject);
                // 设置纯文本内容的邮件正文
                message.setText(body);
                // 保存并生成最终的邮件内容
                message.saveChanges();
                // 设置为debug模式, 可以查看详细的发送 log
                session.setDebug(true);
                // 获取Transport对象
                Transport transport = session.getTransport("smtp");
                // 第2个参数需要填写的是QQ邮箱的SMTP的授权码，什么是授权码，它又是如何设置？
                transport.connect(from, "scxjdhbabaljfeaf");
                // 发送，message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
            } catch (Exception e) {
                return ServerResponse.createByErrorMesage("发送失败");
            }
            //将验证码放入session中
            HttpSession codeSession = req.getSession();
            codeSession.setAttribute("code",code);
            return ServerResponse.createBySuccess("发送成功", code);
        }
        return ServerResponse.createByErrorMesage("您的邮箱格式不正确");
    }

    //另一种方式发送邮件
    public  ServerResponse sendEmailOther(String targetEmail, String msg) {
        isEmail check = new isEmail();
        if (check.isEmail(targetEmail)) {
            try {
                String from = "1095652242@qq.com";//发送邮件的邮箱账号
                String to = targetEmail;//对方邮箱
                String subject = "ITArmy提醒您:您的账户信息如下";//标题
                String body = msg;//这是发送的其他信息
                String smtpHost = "smtp.qq.com";//smtp.qq.com/smtp.sohu.com
                Properties props = new Properties();
                props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议（JavaMail规范要求）
                props.setProperty("mail.smtp.host", smtpHost); // 发件人的邮箱的 SMTP服务器地址
                props.setProperty("mail.smtp.auth", "true"); // 请求认证，参数名称与具体实现有关
                // 创建Session实例对象
                Session session = Session.getDefaultInstance(props);
                // 创建MimeMessage实例对象
                MimeMessage message = new MimeMessage(session);
                // 设置发件人
                message.setFrom(new InternetAddress(from));
                // 设置收件人
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
                // 设置发送日期
                message.setSentDate(new Date());
                // 设置邮件主题
                message.setSubject(subject);
                // 设置纯文本内容的邮件正文
                message.setText(body);
                // 保存并生成最终的邮件内容
                message.saveChanges();
                // 设置为debug模式, 可以查看详细的发送 log
                session.setDebug(true);
                // 获取Transport对象
                Transport transport = session.getTransport("smtp");
                // 第2个参数需要填写的是QQ邮箱的SMTP的授权码，什么是授权码，它又是如何设置？
                transport.connect(from, "scxjdhbabaljfeaf");
                // 发送，message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
            } catch (Exception e) {
                return ServerResponse.createByErrorMesage("发送失败");
            }
        }else{
            return ServerResponse.createByErrorMesage("您的邮箱格式不正确");
        }
        return ServerResponse.createBySuccessMessage("发送成功...");
    }

    //产生随机验证码
    public static String achieveCode() {  //由于数字 1 、 0 和字母 O 、l 有时分不清楚，所以，没有数字 1 、 0
        String[] beforeShuffle = new String[]{"2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F",
                "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a",
                "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
                "w", "x", "y", "z"};
        List list = Arrays.asList(beforeShuffle);//将数组转换为集合
        Collections.shuffle(list);  //打乱集合顺序
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i)); //将集合转化为字符串
        }
        return sb.toString().substring(3, 8);  //截取字符串第4到8
    }
}
